package com.typy.www.tpay.volley;

/**
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.typy.www.tpay.LoginActivity;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.vm.LoginVm;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.constance.MessageEvent;
import com.typy.www.tpay.constance.Sharep;
import com.typy.www.tpay.net.sourceforge.simcpux.MD5;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.MessageAction;
import com.typy.www.tpay.util.ParamsUtil;
import com.typy.www.tpay.util.PreferencesUtil;
import com.typy.www.tpay.util.StringUtil;
import com.typy.www.tpay.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Helper class that is used to provide references to initialized
 * RequestQueue(s) and ImageLoader(s)
 *
 * @author Ognyan Bankov
 */
public class HTTPUtils {
    private static RequestQueue mRequestQueue;

    private HTTPUtils() {
    }

    private static void init(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);

    }

    public static void post(final Context context, final String url, final Map<String, String> params, final VolleyListener listener) {
        Logutil.print("url=="+url);
        StringRequest myReq = new UTFStringRequest(Method.POST, url, new Listener<String>() {
            public void onResponse(String response) {
                if (response.contains("<!DOCTYPE")) {
                    listener.onErrorResponse(new VolleyError());
                    return;
                }
                if (checkToken(context, response, url,params,listener))
                    listener.onResponse(response);
                listener.requestComplete();
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                ToastUtil.show(context, "网络连接失败");
                listener.onErrorResponse(error);
                listener.requestComplete();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params.put("token", PreferencesUtil.getValue(Sharep.TOKEN));
                params.put("shx-timestamp", System.currentTimeMillis() + "");
                final List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(params.entrySet());
                // 重写集合的排序方法：按字母顺序
                Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
                    @Override
                    public int compare(Map.Entry<String, String> stringStringEntry, Map.Entry<String, String> t1) {
                        return (stringStringEntry.getKey().toString().compareTo(t1.getKey()));
                    }
                });
                StringBuilder builder = new StringBuilder();
                for (final Map.Entry<String, String> m : list) {
                    if (!StringUtil.isEmpty(m.getValue())&&!m.getKey().equals("shx-sign"))
                        builder.append(m.getKey()).append("=").append(m.getValue()).append("&");
                }
                builder.delete(builder.length() - 1, builder.length());
                builder.append(Constance.KEY);
                params.put("shx-sign", MD5.getMessageDigest(builder.toString().getBytes()));
                Logutil.print("发送参数==" + params);
                return params;
            }
        };
        if (mRequestQueue == null) {
            init(context);
        }

        // 请用缓存
        myReq.setShouldCache(true);
        // 设置缓存时间10分钟
        // myReq.setCacheTime(10*60);
        mRequestQueue.add(myReq);

    }

    /**
     * @Title: sortMap
     * @Description: 对集合内的数据按key的字母顺序做排序
     */
    public List<Map.Entry<String, String>> sortMap(final Map<String, String> map) {
        final List<Map.Entry<String, String>> infos = new ArrayList<Map.Entry<String, String>>(map.entrySet());

        // 重写集合的排序方法：按字母顺序
        Collections.sort(infos, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> stringStringEntry, Map.Entry<String, String> t1) {
                return (stringStringEntry.getKey().toString().compareTo(t1.getKey()));
            }
        });

        return infos;
    }

    public Map<String, String> getParams(Map<String, String> params) {
        final List<Map.Entry<String, String>> list = sortMap(params);
        StringBuilder builder = new StringBuilder();
        for (final Map.Entry<String, String> m : list) {
            builder.append(m.getKey()).append("=").append(m.getValue()).append("&");
        }
        builder.delete(builder.length() - 1, builder.length());
        builder.append("8aaf09055b7aef71015b7b12d7e50003");
        params.put("shx-sign", MD5.getMessageDigest(builder.toString().getBytes()));
        return params;
    }

    public static void get(Context context, String url,
                           final VolleyListener listener) {
        StringRequest myReq = new UTFStringRequest(Method.GET, url,
                new Listener<String>() {
                    public void onResponse(String response) {
                        Logutil.print("111111111");
                        if (response.contains("<!DOCTYPE")) {
                            listener.onErrorResponse(new VolleyError());
                            listener.requestComplete();
                            Logutil.print("333333");
                            return;
                        }
                        Logutil.print("2222222");
                        listener.onResponse(response);
                        listener.requestComplete();
                    }
                }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                listener.onErrorResponse(error);
                listener.requestComplete();
            }
        });
        if (mRequestQueue == null) {
            init(context);
        }
        mRequestQueue.add(myReq);
    }

    public static RequestQueue getRequestQueue(Context context) {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }

    public static boolean checkToken(Context context, String response, String url,Map<String, String> params,VolleyListener listener) {
        BaseReturn baseReturn = GsonUtils.parseJSON(response, BaseReturn.class);
        if (baseReturn != null && Constance.TOKENINVALID == baseReturn.getCode() && Constance.TOKENINVALIDMSG.equals(baseReturn.getMsg())) {
            getToken(context, url,params,listener);
            return false;
        }
        return true;
    }

    public static void getToken(final Context context, final String url, final Map<String, String> params, final VolleyListener listener) {
        ParamsUtil param = new ParamsUtil();
        param.put("refreshToken", PreferencesUtil.getValue(Sharep.REFRESHTOKEN) );
        HTTPUtils.post(context, Constance.getNewtokenURL(), param.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
//                {"code":200,"msg":"操作成功","data":{"fdCode":"13799254317","token":"1640bbf8afff45bc060103b4d19a6b4b","refreshToken":"1640bbf8affac2b7cecf42a4548b34a3"}}
                LoginVm vm= GsonUtils.parseJSON(ret.getData().toString(),LoginVm.class);
                if(vm!=null){
                    PreferencesUtil.save(Sharep.FDCODE,vm.getFdCode());
                    PreferencesUtil.save(Sharep.TOKEN,vm.getToken());
                    PreferencesUtil.save(Sharep.REFRESHTOKEN,vm.getRefreshToken());
                    rePost(context, url,params,listener);
                }
            }
            @Override
            public void onResponseErr(int code, String msg) {
//                {"msg":"refreshToken失效","code":401,"success":false}
                if (Constance.RETOKENINVALID == code && Constance.RETOKENINVALIDMSG.equals(msg)) {
                    LoginActivity.show(context);
                    EventBus.getDefault().post(new MessageEvent(MessageAction.REFRESHLOGINNAME));
                }
//                else
//                    ToastUtil.show(context, msg);
            }
        });
    }

    public static void rePost(Context context, String url,Map<String, String> params,VolleyListener listener) {
        params.remove("shx-timestamp");
        params.remove("shx-sign");
        params.remove("token");
        params.put("token", PreferencesUtil.getValue( Sharep.TOKEN));
        Logutil.print("rePost"+params.toString());
        HTTPUtils.post(context, url,params,listener);
    }
}
